/**
 * 还可输入多少字符
 * 结构:
 * <div id=''>
 * 		<textarea class="mlength-input"></text>
 * 		<div class="mlength-wrap">
 * 			<span class="mlength-remaining">50</span>characters remaining
 * 		</div>
 * </div>
 * @param
 * options = {
 * 		max: 500,
 *     strict: true  
 * }
 * @author  tanggf
 */
(function($){
	$.fn.mlength = function(options){
		options = $.extend({
			max: 500,
			strict: true
		}, options);
		
		return this.each(function(){
			var $this = $(this);
			var $input = $this.children(":input.mlength-input");
			var $remain = $this.children("div.mlength-wrap").children("span.mlength-remaining");					
			var interval = null;
			//first check
			_check_mlength();
			
			$input.focus(function(){
				if( ! interval){
					interval = _set_check_interval();
				}
			}).blur(function(){
				if(interval){
					clearInterval(interval);
					interval = null;
				}
			});
			
			function _check_mlength(){				
				var value = $input.val();
				var len = value.length;
				var m = options.max - len;
				if(m < 0){
					m = 0;
					if(options.strict){
						$input.val(value.substring(0, options.max));
					}
				}					
				$remain.text(m);				
			}
			
			function _set_check_interval(){
				var interval = setInterval(function(){
					_check_mlength();
				}, 500);
				return interval;
			}
		});	
	};
})(jQuery);